<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="审核状态" prop="status" v-if="false">
        <el-select v-model="queryStatus" placeholder="审核状态" clearable>
          <el-option label="审核中" value="0"></el-option>
          <el-option label="审核通过" value="1"></el-option>
          <el-option label="审核不通过" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--    <el-row v-if="isAdmin" :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                @click="handleDelete(ids)"
            >删除
            </el-button>
          </el-col>
          &lt;!&ndash;      <el-col :span="1.5">
                  <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                  >导出
                  </el-button>
                </el-col>&ndash;&gt;
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>-->

    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column align="center" show-overflow-tooltip label="标题" prop="name"/>
      <el-table-column align="center" show-overflow-tooltip label="首次上传标题" prop="firstName"/>
      <el-table-column align="center" show-overflow-tooltip label="上传人" prop="createUserName"/>
      <!--      <el-table-column show-overflow-tooltip label="来源" prop="origin"/>-->
      <!--      <el-table-column show-overflow-tooltip label="作者" prop="author"/>-->
      <!--      <el-table-column show-overflow-tooltip label="发布日期" prop="createTime"/>-->
      <el-table-column align="center" show-overflow-tooltip label="审核状态" prop="status">
        <template slot-scope="{row}">{{ auditStatusMap[row.status] }}</template>
      </el-table-column>
      <!--      <el-table-column show-overflow-tooltip label="内容" prop="content">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <text-overflow :text="row.content"></text-overflow>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            :disabled="scope.row.status!=0"
            size="mini"
            type="text"
            @click="approveItem(scope.row)"
          >审核
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handlePreview1(scope.row)"
          >预览
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDownload(scope.row)"
          >下载
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.curPage"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog
      title="审核"
      :visible.sync="approveVisible"
      width="60%"
      :before-close="handleClose"
    >
      <div style="margin-bottom: 22px;">审核评论：</div>
      <div>
        <el-input
          type="textarea"
          :rows="10"
          placeholder="请输入内容"
          v-model="approveText"
        >
        </el-input>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="approve('reject')" size="medium">驳回</el-button>
    <el-button type="primary" @click="approve('pass')" size="medium">通过</el-button>
  </span>
    </el-dialog>

    <el-dialog title="查看详情" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" label-suffix="：">
        <el-form-item label="标题" prop="title">
          <span>{{ form.title }}</span>
        </el-form-item>
        <el-form-item label="来源" prop="origin">
          <span>{{ form.origin }}</span>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <span>{{ form.author }}</span>
        </el-form-item>
        <el-form-item label="备注" style="width: 100%" class="fsfdasfsaf">
          <span>{{ form.content }}</span>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 文件预览弹窗 -->
    <el-dialog
      title="在线预览"
      :visible.sync="previewVisible"
      width="60%"
    >
      <vue-office-docx :src="previewUrl" @rendered="rendered"/>
    </el-dialog>
  </div>

</template>

<script>
import {changeRoleStatus, deptTreeSelect} from '@/api/system/role'
import {roleMenuTreeselect} from '@/api/system/menu'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {DomEditor} from '@wangeditor/editor'
import VueOfficeDocx from '@vue-office/docx'
import '@vue-office/docx/lib/index.css'
import TextOverflow from '@/views/qyxx/components/text-overflow.vue'
import {
  auditCurrentTasks,
  createQyxx,
  deleteQyxx,
  editQyxx,
  getApproveSourceData,
  getAuditTaskList,
  getFileEnclosurePath
} from '@/api'
import {mapGetters} from 'vuex'

export default {
  name: 'dp',
  components: {TextOverflow, Editor, Toolbar, VueOfficeDocx},
  dicts: ['sys_normal_disable'],
  data() {
    return {
      queryStatus: '',
      // 遮罩层
      loading: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      tableList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      deptExpand: true,
      deptNodeAll: false,
      // 文件预览
      previewUrl: '',
      // 弹出层是否可见
      previewVisible: false,
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        curPage: 1,
        pageSize: 10,
        status: '',
        myApprove: true,
        name: ''
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表单校验
      rules: {
        title: [
          {required: true, message: '标题不能为空', trigger: 'blur'}
        ],
        scrapeDate: [
          {required: true, message: '爬取日期不能为空', trigger: 'blur'}
        ],
        publishDate: [
          {required: true, message: '发表日期不能为空', trigger: 'blur'}
        ],
        enclosure: [
          {required: true, message: '权限字符不能为空', trigger: 'blur'}
        ],
        listenFileTypeCode: [
          {required: true, message: '权限字符不能为空', trigger: 'blur'}
        ]
      },
      editor: null,
      toolbarConfig: {excludeKeys: ['emotion', 'insertLink', 'group-image', 'group-video']},
      editorConfig: {placeholder: '请输入内容...'},
      mode: 'default', // or 'simple'
      classifyId: this.$route.query.id,
      selectTableList: [],
      ids: [],
      auditStatusMap: {0: '审核中', 1: '审核通过', 2: '审核不通过'},
      approveVisible: false,
      approveText: '',
      approveData: {}
    }
  },

  computed: {...mapGetters(['isAdmin'])},
  created() {
    this.getList()
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      // console.log(this.editor.getAllMenuKeys())
      const toolbar = DomEditor.getToolbar(this.editor)
      // console.log(DomEditor, this)
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true
      getAuditTaskList({
        ...this.queryParams,
        statusList: [this.queryParams.status]
      }).then(res => {
        this.tableList = res.data.records
        this.total = res.data.total
      }).finally(() => {
        this.loading = false
      })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys()
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.menus
        return response
      })
    },
    /** 根据角色ID查询部门树结构 */
    getDeptTree(roleId) {
      return deptTreeSelect(roleId).then(response => {
        this.deptOptions = response.depts
        return response
      })
    },
    // 角色状态修改
    handleStatusChange(row) {
      let text = row.status === '0' ? '启用' : '停用'
      this.$modal.confirm('确认要"' + text + '""' + row.title + '"角色吗？').then(function () {
        return changeRoleStatus(row.roleId, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
      }).catch(function () {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        title: undefined,
        scrapeDate: undefined,
        publishDate: undefined,
        transTitle: undefined,
        keyword: undefined,
        author: undefined,
        language: undefined,
        typeTag: undefined,
        url: undefined,
        abstractStr: undefined,
        transAbstract: undefined,
        fwb: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.curPage = 1
      this.queryParams.status = this.queryStatus
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectTableList = selection
      this.ids = selection.map(item => item.id)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.title = '修改'
      this.open = true
      this.form = {...row}
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let params = {...this.form, classifyId: this.classifyId, listenFileTypeCode: 1}
          let formData = new FormData()
          for (let key in params) {
            if (params[key] !== void 0) {
              formData.append(key, params[key])
            }
          }
          if (this.form.id) {
            editQyxx(formData).then(res => {
              this.open = false
              this.getList()
            })
          } else {
            createQyxx(formData).then(res => {
              this.open = false
              this.getList()
            })
          }
          this.open = false
        }
      })
    },
    /** 获取附件链接 */
    async getEnclosureUrl(row) {
      await getFileEnclosurePath({id: row.mainId}).then(response => {
        this.previewUrl = response.data[0]
      }).catch(error => {
        console.log(error)
      })
    },
    /** 预览按钮操作 */
    handlePreview(row) {
      getApproveSourceData(row.id).then(res => {
        this.form = res.data
        this.open = true
      })
    },
    /** 预览按钮操作 */
    handlePreview1(row) {
      this.previewVisible = true
      this.previewUrl = ''
      this.getEnclosureUrl(row)
    },
    rendered() {
      console.log('渲染完成')
      console.log(this.previewUrl)
    },
    /** 下载文件 */
    downloadFile() {
      const aLink = document.createElement('a')
      aLink.href = this.previewUrl
      aLink.click()
    },
    async handleDownload(row) {
      await this.getEnclosureUrl(row)
      this.downloadFile()
    },
    /** 收藏按钮操作 */
    handleCollection() {
      // TODO 收藏功能
    },

    /** 删除按钮操作 */
    handleDelete(ids) {
      this.$modal.confirm('是否确认删除？').then(() => {
        deleteQyxx(ids).then(res => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/role/export', {
        ...this.queryParams
      }, `role_${new Date().getTime()}.xlsx`)
    },
    approveItem(row) {
      this.approveData = row
      this.approveVisible = true
      this.approveText = ''
    },
    approve(v) {
      auditCurrentTasks({
        'approve': v,
        'auditRemark': this.approveText,
        'auditTaskLevelIds': [this.approveData.id]
      }).then(res => {
        if (res.data.successCount === 1) {
          this.$message.success('审核成功')
          this.getList()
          this.handleClose()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleClose() {
      this.approveVisible = false
    }
  }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss">
.el-tooltip__popper {
  background-color: #fff !important;
  color: #606266 !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1) !important;
  max-width: 600px;
}

/*
.el-table .cell.el-tooltip {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 5;
  display: -moz-box;
  -moz-box-orient: vertical;
  -moz-line-clamp: 5;
  word-break: break-all;
  white-space: normal;
}*/
</style>
